<template>
  <div class="listOder"  >
    <div class="" >
      <el-dialog  :visible.sync="show" width="650px">
        <div>
          <el-form  :model="fromData2" label-width="80px" :rules="languageData.id=='Chinese'?rules3:rules3" ref="fromData2" label-position="right" id="formBox2" >
            <div class="time clearfix" >
              <div class="left status" :class="{'suc':fromData2.ipStatus=='成功','orr':fromData2.ipStatus=='失败','do':fromData2.ipStatus=='执行中'}">
                {{fromData2.ipStatus }}
              </div>
              <div class="left" style="width: 186px" >
                <el-form-item label="IP地址"  style="text-align: left" class="clearfix"  prop="ip">

                  <el-input v-model="fromData2.ip" :disabled="!ipStatus" placeholder="ip地址" style="width: 170px" class="inputDavies left"></el-input>
                </el-form-item>
              </div>
              <div class="left" style="width: 204px">
                <el-form-item   style="text-align: left" class="clearfix"  prop='port'>
                  <el-input v-model="fromData2.port" :disabled="!ipStatus" placeholder="端口号" style="width: 80px;" class="inputDavies left"></el-input>
                </el-form-item>
              </div>
              <div class="right">
                <el-button type="primary" size="mini"    @click="updateDevic('fromData2',1)" v-if="ipStatus">{{languageData.public.done}}</el-button>
                <el-button size="mini"  @click="ipStatus = true" v-if="!ipStatus">{{languageData.public.update}}</el-button>
                <el-button size="mini"  @click="ipStatus = false;fromData2.port = fromDataCopy.port;fromData2.ip = fromDataCopy.ip;"  v-if="ipStatus">{{languageData.public.cancel}}</el-button>
              </div>
            </div>
            <div class="time clearfix">
              <div class="left status" :class="{'suc':fromData2.focationFreqStatus=='成功','orr':fromData2.focationFreqStatus=='失败','do':fromData2.focationFreqStatus=='执行中'}">
                {{fromData2.focationFreqStatus }}
              </div>
              <div class="left">
                <el-form-item label="工作频率"   class="clearfix" style="text-align: left">
                  <el-select  v-model="fromData2.locationFreq" :disabled="!focationFreqStatus" :placeholder="languageData.id=='Chinese'?'请选择':'time'" style="width: 50%" @change="">
                    <el-option v-for="item in options" :key="item.value" :label="languageData.id=='Chinese'?item.label:item.label2" :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </div>
              <div class="right">
                <el-button type="primary" size="mini"    @click="updateDevic('fromData2',2)" v-if="focationFreqStatus">{{languageData.public.done}}</el-button>
                <el-button size="mini"  @click="focationFreqStatus = true" v-if="!focationFreqStatus">{{languageData.public.update}}</el-button>
                <el-button size="mini"  @click="focationFreqStatus = false;fromData2.locationFreq = fromDataCopy.locationFreq"  v-if="focationFreqStatus">{{languageData.public.cancel}}</el-button>
              </div>
            </div>

            <div class="time clearfix">
              <div class="left status" :class="{'suc':fromData2.openStatus=='成功','orr':fromData2.openStatus=='失败','do':fromData2.openStatus=='执行中'}">
                {{fromData2.openStatus }}
              </div>
              <div class="left">
                <el-form-item label="防拆警报"   class="clearfix" style="text-align: left">

                  <el-radio-group v-model="fromData2.isOpen" :disabled="!openStatus" size="mini">
                    <el-radio-button label="1"> 开</el-radio-button>
                    <el-radio-button label="0"> 关</el-radio-button>
                  </el-radio-group>
                </el-form-item>
              </div>
              <!--this.fromDataCopy = {-->
              <!--imei:list.cardNumber || '',-->
              <!--ip:list.ip || '',-->
              <!--port:list.port || '',-->
              <!--frequencyType:'',-->
              <!--locationFreq:list.locationFreq || '',-->
              <!--isOpen:list.isOpen || ''-->
              <!--}-->
              <div class="right">
                <el-button type="primary" size="mini"    @click="updateDevic('fromData2',3)" v-if="openStatus">{{languageData.public.done}}</el-button>
                <el-button size="mini"  @click="openStatus = true"  v-if="!openStatus">{{languageData.public.update}}</el-button>
                <el-button size="mini"  @click="openStatus = false;fromData2.isOpen = fromDataCopy.isOpen"  v-if="openStatus">{{languageData.public.cancel}}</el-button>
              </div>
            </div>
          </el-form>
        </div>

      </el-dialog>
    </div>
    <section id="cent" :languageData="languageData">
      <div class="top" :updateStatusData="updateStatusData">
        <div class="clearfix" style="margin-top: 20px" :adminDeviceShowDeviceData="adminDeviceShowDeviceData">
          <el-form  :model="fromData" label-width="80px" :rules="languageData.id=='Chinese'?rules:rules2" ref="fromData"   label-position="right" id="formBox2" >
            <el-form-item :label="languageData.public.container" prop="number" style="text-align: left" class="clearfix">
                <el-input v-model="fromData.number" :placeholder="languageData.public.container"  class="inputDavies left"></el-input>
                <div class="left bot" style="position: relative">
                  批量导入
                  <input type="file" id="file" style="" @change="fileChange()" accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"/>
                </div>
              <div class="left" style="position: relative;margin-left: 50px;cursor: pointer" @click="down()">
                点击下载Excel模板
              </div>
            </el-form-item>
            <el-form-item :label="languageData.admin.cardNumberL"  class="clearfix" style="text-align: left">
                <el-input v-model="fromData.cardNumber" :placeholder="languageData.admin.cardNumberL"  class="inputDavies"></el-input>
            </el-form-item>
          </el-form>
        </div>
        <div class="clearfix">
          <div class="right okBot" @click="add('fromData')">
             完成
          </div>
        </div>
      </div>
      <div class="center">
         <div class="title">
           <p>设备列表</p>
         </div>
        <div>
          <div class="list" v-for="(list,index) in listData">
            <p class="clearfix" > <span>设备{{index+1 + (10 * (page.page-1))}}：</span><span> {{list.number }}</span>
              <span class="phoneText" v-show="list.cardNumber">卡号： {{list.cardNumber}}</span>
              <span class="del"  @click="del(list)">删除</span>
              <span class="del" style="margin-right: 20px" @click="alerFn(list)">设置</span>
            </p>
          </div>

        </div>
        <div class="page">
          <el-pagination layout="prev, pager, next" :total="page.cunt" v-show="page.cunt>1" @current-change="handleCurrentChange">
          </el-pagination>
        </div>
     </div>
    </section>
    <section id="footer" style="text-align: right">
    </section>
  </div>
</template>
<style scoped>
  .status{width: 42px;height: 40px}
  .suc{color: #13ce66;line-height: 40px;width: 42px}
  .orr{color: red;line-height: 40px;width: 42px}
  .do{color: #0e72b9;line-height: 40px;width: 42px}
  #file{position: absolute;top: 0px;left: 0px;height: 35px;width: 122px;opacity: 0;cursor: pointer }
  .phoneText{ margin-left: 20px}
  .page{position: absolute;bottom: 8px;right: 20px}
  .del{float: right;color: #00a2d4;cursor: pointer}
  .title{margin-bottom: 20px;font-size: 14px;font-weight: bold}
  .list{ border-bottom: 1px solid #e1e1e1;text-align: left;padding: 9px 0px;}
  .list p{ font-size: 14px}
  .okBot{width: 133px;height: 35px;margin-bottom: 20px;background-color: #0e72b8;border-color: #0e72b8;
    color: #fff;border-radius: 20px;line-height: 35px;font-size: 14px;margin-top: 60px}
  .okBot:hover{background-color: #409eff;border-color: #409eff;  }

  .bot{border: 1px solid #dcdfe6;height: 35px;width: 122px;margin-left: 66px;margin-top: 2px;cursor: pointer;
    background: url("../../../static/img/excl.png") no-repeat;background-position: 15px 7px;box-sizing: border-box;
    padding: 0px 20px 0px 43px;font-size: 14px;line-height: 35px;overflow: hidden;
  }
  label{line-height: 40px;font-size: 14px}
  .inputDavies{width: 390px;height: 40px;}
  #cent{background-color: #f7f7f7}
.top{ width: 930px;height: 296px;box-sizing: border-box;background-color:#fff;margin: 0px auto;margin-top: 20px;border-radius: 6px;
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);padding: 40px 20px 40px 40px}
.center{width: 930px;height: 500px;box-sizing: border-box;background-color:#fff;margin: 0px auto;margin-top: 20px;border-radius: 6px;
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);padding: 40px 20px 40px 40px;text-align: left;position: relative;margin-bottom: 40px}
  @media only screen and (min-width: 300px){
    .cardBox{margin-left:100px;}
  }
  @media only screen and (min-width: 1200px){
    .cardBox{width:100%;min-width: 920px;max-width:1100px;padding: 40px;min-height: 400px;margin:0px auto;}
  }
</style>
<script>
  import {mapState, mapActions} from 'vuex'
  import ElButton from "../../../node_modules/element-ui/packages/button/src/button.vue";
  import Blob from '../../vendor/Blob.js'
  import Export2Excel from '../../vendor/Export2Excel'
  export default {
    name: 'my-Chart',
    created () {
      // 查看本页面路由 绑定对应页面class
      var usr = sessionStorage.getItem('user')
      if(usr) {
        usr = JSON.parse(usr)
        this.user = usr
      }
    },
    data () {
      return {
        index:'',
        focationFreqStatus:false,
        openStatus :false,
        ipStatus:false,
        show:false,
        fromData: {
          number:'',
          cardNumber:''
        },
        //  ，，，
        fromData2:{
          ip:'192.168.1.168',
          port:'8000',
          frequencyType:'',
          locationFreq:'8 小时',
          imei:"",
          isOpen:'1'
        },
        fromDataCopy:{
          ip:'192.168.1.168',
          port:'8000',
          frequencyType:'',
          locationFreq:'12 小时',
          isOpen:'1'
        },
        companyId:'',
        page: {
          page: 1,
          pageSize: 10,
          cunt: 0
        },
        listData:[],
        rules: {
          number: [
            { required: true ,message:'Please fill IMEI No.', trigger: 'blur' }
          ],
          cardNumber: [
            { required: true, message: 'Please fill card No.', trigger: 'blur' }
          ],
        },
        rules2: {
          number: [
            { required: true ,message:'Please fill IMEI No.', trigger: 'blur' }
          ],
          cardNumber: [
            { required: true, message: 'Please fill card No.', trigger: 'blur' }
          ],
        },
        rules3: {
          ip: [{ validator:(rule, value, callback) =>{
              var regEn =/^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/ ;
              if(regEn.test(value)){callback();
              }else if(value === '' && this.fromData2.port==''){
                callback();
              }else {
                callback(new Error('请输入正确的ip地址'));
              }
            }, trigger: 'blur' }],
          port: [
            { validator:(rule, value, callback) =>{
                var regEn =/^(\d)+$/g ;
                if(regEn.test(value) && parseInt(value)<=65535&&parseInt(value)>=0 ){
                  callback();
                }else if(value === '' && this.fromData2.ip==''){
                  callback();
                }else {
                  callback(new Error('请输入正确的端口号'));
                }
              }, trigger: 'blur' }
          ],
        },
        options: [{
          value: '1 小时',
          label: '1 小时',
          label2: '1 hour'
        }, {
          value: '2 小时',
          label: '2 小时',
          label2: '2 hour'
        }, {
          value: '3 小时',
          label: '3 小时',
          label2: '3 hour'
        }, {
          value: '6 小时',
          label: '6 小时',
          label2: '6 hour'
        }, {
          value: '8 小时',
          label: '8 小时',
          label2: '8 hour'
        }, {
          value: '12 小时',
          label: '12 小时',
          label2: '12 hour'
        }, {
          value: '1天',
          label: '1天',
          label2: '1 day'
        }],
      }
    },
    methods: {
      ...mapActions({
        deviceShowList: 'deviceShowList',
        addDevice:'addDevice',
        deleteDevice:'deleteDevice',
        sendDictate:'sendDictate'
      }),

      rul(){
        var tex = ''
      },
      down(){
        window.location = 'http://www.bluecargoo.com/moban/deviceTemplate.xlsx'
        // window.open('http://www.bluecargoo.com/moban/deviceTemplate.xlsx','height=100, width=400, top=0, left=0, toolbar=no, menubar=no, scrollbars=no, resizable=no, location=no, status=no')
      },
      // 分页
      handleCurrentChange (val) {
        this.page.page = parseInt(val)

        this.saechList()
      },
      // 频率

      fileChange(obj) {
        let _this = this;
        let inputDOM = this.$refs.inputer;
        // 通过DOM取文件数据
        this.file = event.currentTarget.files[0];
        var rABS = false; //是否将文件读取为二进制字符串
          var f = this.file;
          var reader = new FileReader();
          //if (!FileReader.prototype.readAsBinaryString) {
          FileReader.prototype.readAsBinaryString = function(f) {
            var binary = "";
            var rABS = false; //是否将文件读取为二进制字符串
            var pt = this;
            var wb; //读取完成的数据
            var outdata;
            var reader = new FileReader();
            reader.onload = function(e) {
              var bytes = new Uint8Array(reader.result);
              var length = bytes.byteLength;

              for(var i = 0; i < length; i++) {
                binary += String.fromCharCode(bytes[i]);
              }
              var XLSX = require('xlsx');

              if(rABS) {
                wb = XLSX.read(btoa(fixdata(binary)), { //手动转化
                  type: 'base64'
                });
              } else {
                wb = XLSX.read(binary, {
                  type: 'binary'
                });
                console.log(wb)
              }
              outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);//outdata就是你想要的东西
              this.da = [...outdata]
              let arr = []
              this.da.map(v => {
                console.log(v,'v')
                let obj = {
                  companyId:_this.companyId,
                  number:v['设备号'],
                  cardNumber:v['卡号']
                }
                arr.push(obj)
              })
              console.log(arr)
              _this.$message({
                message: '请耐心等待导入成功',
                type: 'success'
              });
            _this.addDevice(arr)
            }
            reader.readAsArrayBuffer(f);
          }
          if(rABS) {
            reader.readAsArrayBuffer(f);
          } else {
            reader.readAsBinaryString(f);
          }
        },

      //
      saechList () {
        this.loading = true
        var parm={
          companyId:this.companyId,
          page:this.page.page,
          pageSize:this.page.pageSize
        }
        this.deviceShowList(parm);
      },
      // 查询按钮
      saechFn () {
        this.pages.page = 1
        this.saechList()
      },
      // 请求状态
      listStatus (res) {
        console.log(res,'res')
        if (res.status == 0) {
          // 修改成功
          if(res.code == 'deleteDevice'){
            var  text = ''
            if(this.languageData.id == 'Chinese'){
              text = '删除成功'
            }else {
              text = 'delete complete'
            }
            this.openSuccess(text)
            this.saechList(this.id)
          }else if(res.code == 'addDevice'){
            text = this.languageData.id=='Chinese'?'添加成功': 'Update successfully'
            this.openSuccess(text)
            this.saechList()
          }else if(res.code == 'sendDictate'){
            text = this.languageData.id=='Chinese'?'修改成功': 'Update successfully';
            this.openSuccess(text)
            this.saechList()
            if(this.index == 1){
              this.fromData2.ipStatus = "执行中"
              this.fromDataCopy.ip = this.fromData2.ip
              this.fromDataCopy.port = this.fromData2.port
            }
            if(this.index == 2){
              this.fromData2.focationFreqStatus= "执行中";
              this.fromDataCopy.locationFreq = this.fromData2.locationFreq
            }
            if(this.index == 3){
              this.fromData2.openStatus= "执行中"
              this.fromDataCopy.isOpen = this.fromData2.isOpen
            }
          }
        }else  {
          // 修改成功
          if(res.code == 'deleteDevice'){
            var  text = ''
            if(this.languageData.id == 'Chinese'){
              text = '删除失败'
            }else {
              text = 'delete complete'
            }
            this.openError(text)
          }else if(res.code == 'addDevice'){
            text = this.languageData.id=='Chinese'?'添加失败': 'Update fail'
            this.openError(text)
          }else if(res.code == 'sendDictate'){
            text = this.languageData.id=='Chinese'?'修改失败': 'Update fail'
            this.openError(text)
          }
        }
        // 清空 vuex 中的本次记录，以免被下次操作状态造成混淆
        this.$store.commit('updateStatusTo', {body: null})
      },
      add(formName,a) {
        this.$refs[formName].validate((valid) => {
            if (valid) {
              var parm = [{
                companyId:this.companyId,
                number:this.fromData.number,
                cardNumber:this.fromData.cardNumber
              }]
              this.addDevice(parm)
            } else {
              console.log('error submit!!')
              return false
            }
        })


      },
      del(list){
        var parm = {

          deviceId:list.id
        }
        this.deleteDevice(parm)
      },
      openSuccess (text) {
        this.$message({
          message: text,
          type: 'success'
        })
      },
      openError (text) {
        this.$message({
          message: text,
          type: 'error'
        })
      },
      // 列表数据解析
      deviceListFn(res){
        if(res.code == 'DeviceShowList'){
          this.page.cunt = res.body.count
          res = res.body.data
          var pu = []
          for(let i in res){
            if(res[i].frequencyType == 1){
              res[i].locationFreq = res[i].locationFreq +"分钟"
            }
            if(res[i].frequencyType == 2){
              res[i].locationFreq = res[i].locationFreq +"小时"
            }
            if(res[i].frequencyType == 3){
              res[i].locationFreq = res[i].locationFreq +"天"
            }
            res[i].ipStatus = res[i].ipStatus == 1 ? '执行中': res[i].ipStatus == 2 ? '成功': res[i].ipStatus == 3 ? '失败':''
            res[i].focationFreqStatus = res[i].focationFreqStatus == 1 ? '执行中': res[i].focationFreqStatus == 2 ? '成功': res[i].focationFreqStatus ==3 ? '失败':''
            res[i].openStatus = res[i].openStatus == 1 ? '执行中': res[i].openStatus == 2 ? '成功':res[i].openStatus == 3 ? '失败':''

          }
          this.listData = res
        }else {
          this.listData = []
        }
      },
      // 修改设备
      updateDevic(formName,a){

        this.$refs[formName].validate((valid) => {
          if (valid) {
            var parm ={
              imei:this.fromData2.imei,
              ip:'',
              port:'',
              frequencyType:'',
              locationFreq:'',
              isOpen:''
            };
            // 判断熟悉是否修改
            this.index = a
            if(a==1  ){
              if(!this.fromData2.ip || !this.fromData2.port){

                return
              }
              parm.ip = this.fromData2.ip;
              parm.port = this.fromData2.port;
              this.ipStatus = false;

            };
            // 判断 频率 分离单位
            console.log(this.fromData2.locationFreq,this.fromDataCopy.locationFreq)
            if(a==2){
              parm.locationFreq = this.fromData2.locationFreq
              if(!parm.locationFreq ){
                return
              }
              if (parm.locationFreq.indexOf('分钟') > 0) {
                parm.frequencyType = 1;
              }
              if (parm.locationFreq.indexOf('小时') > 0) {
                parm.frequencyType = 2;
              }
              if (parm.locationFreq.indexOf('天') > 0) {
                parm.frequencyType = 3;
              }
              parm.locationFreq = parseInt(parm.locationFreq)
              this.focationFreqStatus = false;

            }
            if(a==3){
              if( parseInt(this.fromData2.isOpen) ===0 ||  parseInt(this.fromData2.isOpen) ===1 ){
                parm.isOpen = parseInt(this.fromData2.isOpen)
                this.openStatus = false;
              }else {
                return
              }
            }
            // console.log(parm)
            this.sendDictate(parm)
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      // 弹框
      alerFn(list){
        this.fromData2 = {
          imei:list.number || '',
          ip:list.ip || '',
          port:list.port || '',
          frequencyType:'',
          locationFreq:list.locationFreq || '',
          isOpen:list.isOpen || '',
          ipStatus : list.ipStatus,
          focationFreqStatus : list.focationFreqStatus,
          openStatus : list.openStatus
        }
        this.fromDataCopy = {
          imei:list.cardNumber || '',
          ip:list.ip || '',
          port:list.port || '',
          frequencyType:'',
          locationFreq:list.locationFreq || '',
          isOpen:list.isOpen || ''
        }
        this.show = true
      }
    },
    computed: {
      updateStatusData: function () {
        var parm = this.updateStatus
        if (parm) {
          this.listStatus(parm)
        }
        return 1
      },
      languageData: function () {
        var parm = this.language
        if (parm) {
          if (parm.check == 'Chinese') {
            parm = parm.Chinese
          }
          if (parm.check == 'English') {
            parm = parm.English
//            this.formConfig.labelWidth = '200px'
//            dom.style = 'width:620px'
          }
          // 替换 其他交互数据
//          this.updateDate(parm)
        }
        return parm
      },
      adminDeviceShowDeviceData:function(){
       var parm =  this.adminDeviceShowList;
       if(parm){
         this.deviceListFn(parm)
       }
      },
      ...mapState([
        'updateStatus',
        'language',
        'adminDeviceShowList'
      ])
    },
    mounted () {
      this.companyId = parseInt(this.$route.query.id)
      this.saechList()
    },
    components: {
      ElButton,
    }
  }
</script>

